<template>
  <div class="operation-statistics">
    <div class="main-content">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>运营数据统计</span>
            <el-button-group>
              <el-button type="primary" @click="refreshData"
                >刷新数据</el-button
              >
              <el-button type="success" @click="exportData">导出数据</el-button>
              <el-button
                type="warning"
                @click="openAnalysisDialog"
                :loading="isAnalyzing"
              >
                <el-icon><ChatDotRound /></el-icon>分析数据
              </el-button>
            </el-button-group>
          </div>
        </template>

        <!-- 时间范围选择 -->
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="统计时间">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :shortcuts="dateShortcuts"
              @change="handleDateChange"
            />
          </el-form-item>
        </el-form>

        <!-- 核心指标 -->
        <div class="core-metrics">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-card shadow="hover">
                <template #header>
                  <div class="metric-header">
                    <span>用户总数</span>
                    <el-tag>用户</el-tag>
                  </div>
                </template>
                <div class="metric-value">{{ metrics.totalUsers }}</div>
                <div class="metric-compare">
                  较上期
                  <span :class="metrics.userGrowth >= 0 ? 'up' : 'down'">
                    {{ metrics.userGrowth >= 0 ? "+" : ""
                    }}{{ metrics.userGrowth }}%
                  </span>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card shadow="hover">
                <template #header>
                  <div class="metric-header">
                    <span>订单总数</span>
                    <el-tag type="success">订单</el-tag>
                  </div>
                </template>
                <div class="metric-value">{{ metrics.totalOrders }}</div>
                <div class="metric-compare">
                  较上期
                  <span :class="metrics.orderGrowth >= 0 ? 'up' : 'down'">
                    {{ metrics.orderGrowth >= 0 ? "+" : ""
                    }}{{ metrics.orderGrowth }}%
                  </span>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card shadow="hover">
                <template #header>
                  <div class="metric-header">
                    <span>商家总数</span>
                    <el-tag type="warning">商家</el-tag>
                  </div>
                </template>
                <div class="metric-value">{{ metrics.totalMerchants }}</div>
                <div class="metric-compare">
                  较上期
                  <span :class="metrics.merchantGrowth >= 0 ? 'up' : 'down'">
                    {{ metrics.merchantGrowth >= 0 ? "+" : ""
                    }}{{ metrics.merchantGrowth }}%
                  </span>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card shadow="hover">
                <template #header>
                  <div class="metric-header">
                    <span>景点总数</span>
                    <el-tag type="danger">景点</el-tag>
                  </div>
                </template>
                <div class="metric-value">{{ metrics.totalSpots }}</div>
                <div class="metric-compare">
                  较上期
                  <span :class="metrics.spotGrowth >= 0 ? 'up' : 'down'">
                    {{ metrics.spotGrowth >= 0 ? "+" : ""
                    }}{{ metrics.spotGrowth }}%
                  </span>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>

        <!-- 图表展示 -->
        <div class="charts-container">
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="chart-wrapper">
                <div class="chart-title">用户增长趋势</div>
                <div class="chart" ref="userChartRef"></div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="chart-wrapper">
                <div class="chart-title">订单分布</div>
                <div class="chart" ref="orderChartRef"></div>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20" class="mt-4">
            <el-col :span="12">
              <div class="chart-wrapper">
                <div class="chart-title">商家分类统计</div>
                <div class="chart" ref="merchantChartRef"></div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="chart-wrapper">
                <div class="chart-title">景点热度排行</div>
                <div class="chart" ref="spotChartRef"></div>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-card>
    </div>

    <!-- AI分析助手弹出框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="false"
      width="60%"
      :close-on-click-modal="false"
      destroy-on-close
      top="5vh"
      class="ai-analysis-dialog"
    >
      <template #header>
        <div class="analysis-dialog-header">
          <div class="header-left">
            <div class="ai-avatar">
              <el-icon><ChatDotRound /></el-icon>
            </div>
            <div class="header-title">
              <span>AI 数据分析助手</span>
              <div class="header-subtitle">智能解读数据，挖掘业务洞察</div>
            </div>
          </div>
          <div class="header-actions">
            <el-button-group>
              <el-tooltip content="基础分析" placement="top">
                <el-button 
                  type="primary" 
                  :icon="DataAnalysis" 
                  @click="analyzeData"
                  :loading="isAnalyzing"
                >基础分析</el-button>
              </el-tooltip>
              <el-tooltip content="同比分析" placement="top">
                <el-button 
                  type="info" 
                  :icon="TrendCharts" 
                  @click="analyzeYearOverYear"
                  :loading="isAnalyzingYoY"
                >同比分析</el-button>
              </el-tooltip>
              <el-tooltip content="环比分析" placement="top">
                <el-button 
                  type="success" 
                  :icon="Histogram" 
                  @click="analyzeMonthOverMonth"
                  :loading="isAnalyzingMoM"
                >环比分析</el-button>
              </el-tooltip>
            </el-button-group>
          </div>
        </div>
      </template>
      
      <div class="analysis-dialog-body">
        <el-empty v-if="chatMessages.length === 0" description="点击上方按钮开始分析数据">
          <el-button type="primary" @click="analyzeData">开始分析</el-button>
        </el-empty>
        
        <div v-else class="analysis-messages">
          <div
            v-for="(message, index) in chatMessages"
            :key="index"
            class="message"
            :class="[message.type, message.analysisType.toLowerCase().replace(' ', '-')]"
          >
            <div class="message-header">
              <div class="message-left">
                <div class="message-icon">
                  <el-icon v-if="message.analysisType === '基础分析'"><DataAnalysis /></el-icon>
                  <el-icon v-else-if="message.analysisType === '同比分析'"><TrendCharts /></el-icon>
                  <el-icon v-else-if="message.analysisType === '环比分析'"><Histogram /></el-icon>
                </div>
                <span class="message-type">{{ message.analysisType }}</span>
              </div>
              <span class="message-time">{{ message.time }}</span>
            </div>
            <div class="message-content">{{ message.content }}</div>
            <div class="message-actions">
              <el-button-group size="small">
                <el-tooltip content="导出分析报告" placement="top">
                  <el-button :icon="Download" link @click="exportAnalysis(message)">导出</el-button>
                </el-tooltip>
                <el-tooltip content="生成图表" placement="top">
                  <el-button :icon="PieChart" link @click="generateChart(message)">生成图表</el-button>
                </el-tooltip>
                <el-tooltip content="分享结果" placement="top">
                  <el-button :icon="Share" link @click="shareAnalysis(message)">分享</el-button>
                </el-tooltip>
              </el-button-group>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="analysis-dialog-footer">
          <span class="ai-powered">由 AI 提供数据洞察支持</span>
          <el-button @click="dialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 图表预览弹窗 -->
    <el-dialog
      v-model="chartDialogVisible"
      title="分析数据可视化"
      width="70%"
      :close-on-click-modal="true"
      destroy-on-close
      center
    >
      <div class="chart-preview" ref="previewChartRef"></div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, onUnmounted, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import * as echarts from "echarts";
import { debounce } from "lodash-es";
import { 
  ChatDotRound, 
  DataAnalysis, 
  TrendCharts, 
  Histogram, 
  Download, 
  PieChart, 
  Share 
} from "@element-plus/icons-vue";

// 搜索表单
const searchForm = reactive({
  dateRange: [],
});

// 日期快捷选项
const dateShortcuts = [
  {
    text: "最近一周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: "最近一月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
  {
    text: "最近三月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    },
  },
];

// 核心指标数据
const metrics = reactive({
  totalUsers: 45678,
  totalOrders: 12860,
  totalMerchants: 268,
  totalSpots: 156,
  userGrowth: 15.4,
  orderGrowth: 8.2,
  merchantGrowth: 5.8,
  spotGrowth: -2.3,
});

// 图表实例
const userChartRef = ref(null);
const orderChartRef = ref(null);
const merchantChartRef = ref(null);
const spotChartRef = ref(null);
let userChart = null;
let orderChart = null;
let merchantChart = null;
let spotChart = null;

// 表格数据
const activeTab = ref("users");
const userAnalysis = ref([
  {
    date: "2024-03-01",
    newUsers: 156,
    activeUsers: 3420,
    totalUsers: 45678,
    verifiedUsers: 32145,
    retention: 85.6,
  },
  {
    date: "2024-03-02",
    newUsers: 142,
    activeUsers: 3380,
    totalUsers: 45820,
    verifiedUsers: 32256,
    retention: 84.8,
  },
  {
    date: "2024-03-03",
    newUsers: 168,
    activeUsers: 3510,
    totalUsers: 45988,
    verifiedUsers: 32380,
    retention: 86.2,
  },
]);

const orderAnalysis = ref([
  {
    date: "2024-03-01",
    totalOrders: 586,
    ticketOrders: 320,
    hotelOrders: 156,
    packageOrders: 110,
    completionRate: 94.5,
  },
  {
    date: "2024-03-02",
    totalOrders: 624,
    ticketOrders: 345,
    hotelOrders: 168,
    packageOrders: 111,
    completionRate: 95.2,
  },
  {
    date: "2024-03-03",
    totalOrders: 598,
    ticketOrders: 328,
    hotelOrders: 162,
    packageOrders: 108,
    completionRate: 93.8,
  },
]);

const merchantAnalysis = ref([
  {
    date: "2024-03-01",
    newMerchants: 5,
    activeMerchants: 186,
    totalMerchants: 268,
    verifiedMerchants: 245,
    rating: 4.6,
  },
  {
    date: "2024-03-02",
    newMerchants: 3,
    activeMerchants: 182,
    totalMerchants: 271,
    verifiedMerchants: 247,
    rating: 4.5,
  },
  {
    date: "2024-03-03",
    newMerchants: 4,
    activeMerchants: 188,
    totalMerchants: 275,
    verifiedMerchants: 250,
    rating: 4.7,
  },
]);

const spotAnalysis = ref([
  {
    date: "2024-03-01",
    totalSpots: 156,
    activeSpots: 142,
    visitCount: 12580,
    orderCount: 856,
    rating: 4.8,
  },
  {
    date: "2024-03-02",
    totalSpots: 156,
    activeSpots: 140,
    visitCount: 13240,
    orderCount: 912,
    rating: 4.7,
  },
  {
    date: "2024-03-03",
    totalSpots: 156,
    activeSpots: 144,
    visitCount: 12860,
    orderCount: 886,
    rating: 4.8,
  },
]);

const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(28);

// 日期变化处理
const handleDateChange = () => {
  loadData();
};

// 刷新数据
const refreshData = () => {
  loadData();
  ElMessage.success("数据已更新");
};

// 导出数据
const exportData = () => {
  // 实现导出逻辑
};

// 初始化图表
const initCharts = () => {
  // 确保DOM已经渲染
  if (
    !userChartRef.value ||
    !orderChartRef.value ||
    !merchantChartRef.value ||
    !spotChartRef.value
  ) {
    return;
  }

  nextTick(() => {
    const isDarkMode =
      document.documentElement.getAttribute("data-theme") === "dark";
    const tooltipBackgroundColor = isDarkMode
      ? "rgba(30, 30, 30, 0.9)"
      : "rgba(255, 255, 255, 0.9)";
    const tooltipBorderColor = isDarkMode ? "#434343" : "#eee";
    const tooltipTextColor = isDarkMode ? "#fff" : "#333";

    // 统一的图表配置
    const chartOptions = {
      renderer: "canvas",
      devicePixelRatio: window.devicePixelRatio,
    };

    // 用户增长趋势图
    if (!userChart) {
      try {
        userChart = echarts.init(userChartRef.value, null, chartOptions);
        const userOption = {
          title: {
            text: "用户增长趋势",
            textStyle: {
              color: "var(--el-text-color-primary)",
              fontSize: 16,
              fontWeight: "normal",
            },
          },
          tooltip: {
            trigger: "axis",
            backgroundColor: tooltipBackgroundColor,
            borderColor: tooltipBorderColor,
            textStyle: {
              color: tooltipTextColor,
            },
            axisPointer: {
              type: "line",
              lineStyle: {
                color: isDarkMode ? "#6e7079" : "#ccc",
                width: 1,
              },
            },
          },
          legend: {
            data: ["新增用户", "活跃用户", "累计用户"],
            textStyle: {
              color: "var(--el-text-color-regular)",
            },
          },
          grid: {
            left: "3%",
            right: "4%",
            bottom: "3%",
            containLabel: true,
          },
          xAxis: {
            type: "category",
            boundaryGap: false,
            data: ["1月", "2月", "3月", "4月", "5月", "6月"],
            axisLine: {
              lineStyle: {
                color: "var(--el-border-color)",
              },
            },
            axisLabel: {
              color: "var(--el-text-color-regular)",
            },
          },
          yAxis: {
            type: "value",
            axisLine: {
              show: true,
              lineStyle: {
                color: "var(--el-border-color)",
              },
            },
            splitLine: {
              lineStyle: {
                color: "var(--el-border-color-lighter)",
                type: "dashed",
              },
            },
            axisLabel: {
              color: "var(--el-text-color-regular)",
            },
          },
          series: [
            {
              name: "新增用户",
              type: "line",
              smooth: true,
              data: [120, 132, 101, 134, 90, 230],
              itemStyle: {
                color: "#409EFF",
              },
              areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: "rgba(64, 158, 255, 0.3)" },
                  { offset: 1, color: "rgba(64, 158, 255, 0.1)" },
                ]),
              },
            },
            {
              name: "活跃用户",
              type: "line",
              smooth: true,
              data: [220, 182, 191, 234, 290, 330],
              itemStyle: {
                color: "#67C23A",
              },
              areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: "rgba(103, 194, 58, 0.3)" },
                  { offset: 1, color: "rgba(103, 194, 58, 0.1)" },
                ]),
              },
            },
            {
              name: "累计用户",
              type: "line",
              smooth: true,
              data: [320, 332, 301, 334, 390, 430],
              itemStyle: {
                color: "#E6A23C",
              },
              areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: "rgba(230, 162, 60, 0.3)" },
                  { offset: 1, color: "rgba(230, 162, 60, 0.1)" },
                ]),
              },
            },
          ],
        };
        userChart.setOption(userOption);
      } catch (error) {
        console.error("Failed to initialize user chart:", error);
      }
    }

    // 订单分布图
    if (!orderChart) {
      try {
        orderChart = echarts.init(orderChartRef.value, null, chartOptions);
        const orderOption = {
          title: {
            text: "订单分布",
            textStyle: {
              color: "var(--el-text-color-primary)",
              fontSize: 16,
              fontWeight: "normal",
            },
          },
          tooltip: {
            trigger: "item",
            formatter: "{b}: {c} ({d}%)",
            backgroundColor: tooltipBackgroundColor,
            borderColor: tooltipBorderColor,
            textStyle: {
              color: tooltipTextColor,
            },
          },
          legend: {
            orient: "vertical",
            right: "5%",
            top: "center",
            textStyle: {
              color: "var(--el-text-color-regular)",
            },
          },
          series: [
            {
              name: "订单分布",
              type: "pie",
              radius: ["40%", "70%"],
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 10,
                borderColor: isDarkMode ? "#2b2b2b" : "#fff",
                borderWidth: 2,
              },
              label: {
                show: false,
                position: "center",
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: 20,
                  fontWeight: "bold",
                },
              },
              labelLine: {
                show: false,
              },
              data: [
                { value: 1048, name: "门票", itemStyle: { color: "#409EFF" } },
                { value: 735, name: "酒店", itemStyle: { color: "#67C23A" } },
                { value: 580, name: "套餐", itemStyle: { color: "#E6A23C" } },
                { value: 484, name: "餐饮", itemStyle: { color: "#F56C6C" } },
                { value: 300, name: "其他", itemStyle: { color: "#909399" } },
              ],
            },
          ],
        };
        orderChart.setOption(orderOption);
      } catch (error) {
        console.error("Failed to initialize order chart:", error);
      }
    }

    // 商家分类统计图
    if (!merchantChart) {
      try {
        merchantChart = echarts.init(
          merchantChartRef.value,
          null,
          chartOptions,
        );
        const merchantOption = {
          title: {
            text: "商家分类统计",
            textStyle: {
              color: "var(--el-text-color-primary)",
              fontSize: 16,
              fontWeight: "normal",
            },
          },
          tooltip: {
            trigger: "axis",
            axisPointer: {
              type: "shadow",
            },
            backgroundColor: tooltipBackgroundColor,
            borderColor: tooltipBorderColor,
            textStyle: {
              color: tooltipTextColor,
            },
          },
          grid: {
            left: "3%",
            right: "4%",
            bottom: "3%",
            containLabel: true,
          },
          xAxis: {
            type: "value",
            axisLine: {
              lineStyle: {
                color: "var(--el-border-color)",
              },
            },
            splitLine: {
              lineStyle: {
                color: "var(--el-border-color-lighter)",
                type: "dashed",
              },
            },
            axisLabel: {
              color: "var(--el-text-color-regular)",
            },
          },
          yAxis: {
            type: "category",
            data: ["餐饮", "住宿", "购物", "娱乐", "文化"],
            axisLine: {
              lineStyle: {
                color: "var(--el-border-color)",
              },
            },
            axisLabel: {
              color: "var(--el-text-color-regular)",
            },
          },
          series: [
            {
              name: "商家数量",
              type: "bar",
              data: [120, 200, 150, 80, 70],
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                  { offset: 0, color: "#409EFF" },
                  { offset: 1, color: "#67C23A" },
                ]),
                borderRadius: [0, 4, 4, 0],
              },
            },
          ],
        };
        merchantChart.setOption(merchantOption);
      } catch (error) {
        console.error("Failed to initialize merchant chart:", error);
      }
    }

    // 景点热度排行图
    if (!spotChart) {
      try {
        spotChart = echarts.init(spotChartRef.value, null, chartOptions);
        const spotOption = {
          title: {
            text: "景点热度排行",
            textStyle: {
              color: "var(--el-text-color-primary)",
              fontSize: 16,
              fontWeight: "normal",
            },
          },
          tooltip: {
            trigger: "axis",
            axisPointer: {
              type: "shadow",
            },
            backgroundColor: tooltipBackgroundColor,
            borderColor: tooltipBorderColor,
            textStyle: {
              color: tooltipTextColor,
            },
          },
          grid: {
            left: "3%",
            right: "4%",
            bottom: "3%",
            containLabel: true,
          },
          xAxis: {
            type: "value",
            axisLine: {
              lineStyle: {
                color: "var(--el-border-color)",
              },
            },
            splitLine: {
              lineStyle: {
                color: "var(--el-border-color-lighter)",
                type: "dashed",
              },
            },
            axisLabel: {
              color: "var(--el-text-color-regular)",
            },
          },
          yAxis: {
            type: "category",
            data: ["景点A", "景点B", "景点C", "景点D", "景点E"],
            axisLine: {
              lineStyle: {
                color: "var(--el-border-color)",
              },
            },
            axisLabel: {
              color: "var(--el-text-color-regular)",
            },
          },
          series: [
            {
              name: "访问量",
              type: "bar",
              data: [1200, 800, 600, 400, 300],
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                  { offset: 0, color: "#E6A23C" },
                  { offset: 1, color: "#F56C6C" },
                ]),
                borderRadius: [0, 4, 4, 0],
              },
              label: {
                show: true,
                position: "right",
                color: isDarkMode ? "#E5EAF3" : "#606266",
              },
            },
          ],
        };
        spotChart.setOption(spotOption);
      } catch (error) {
        console.error("Failed to initialize spot chart:", error);
      }
    }
  });
};

// 防抖处理的重绘函数
const debouncedResize = debounce(() => {
  const charts = [userChart, orderChart, merchantChart, spotChart];
  charts.forEach((chart) => {
    if (chart) {
      try {
        chart.resize();
      } catch (error) {
        console.error("Failed to resize chart:", error);
      }
    }
  });
}, 100);

// 监听主题变化
const handleThemeChange = debounce(() => {
  const charts = [userChart, orderChart, merchantChart, spotChart];
  charts.forEach((chart) => {
    if (chart) {
      try {
        chart.dispose();
      } catch (error) {
        console.error("Failed to dispose chart:", error);
      }
    }
  });
  userChart = null;
  orderChart = null;
  merchantChart = null;
  spotChart = null;
  initCharts();
}, 100);

// 加载数据
const loadData = () => {
  // 实现数据加载逻辑
  nextTick(() => {
    initCharts();
  });
};

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  loadData();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  loadData();
};

// 页面加载时获取数据
onMounted(() => {
  loadData();
  window.addEventListener("resize", debouncedResize);
  window.addEventListener("theme-change", handleThemeChange);
});

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener("resize", debouncedResize);
  window.removeEventListener("theme-change", handleThemeChange);

  // 清理防抖函数
  debouncedResize.cancel();
  handleThemeChange.cancel();

  const charts = [userChart, orderChart, merchantChart, spotChart];
  charts.forEach((chart) => {
    if (chart) {
      try {
        chart.dispose();
      } catch (error) {
        console.error("Failed to dispose chart:", error);
      }
    }
  });
});

// AI助手相关的状态
const dialogVisible = ref(false);
const chatMessages = ref([]);
const chatContainer = ref(null);
const isAnalyzing = ref(false);
const isAnalyzingYoY = ref(false);
const isAnalyzingMoM = ref(false);
const chartDialogVisible = ref(false);
const previewChartRef = ref(null);
let previewChart = null;

// 打开分析弹窗
const openAnalysisDialog = () => {
  dialogVisible.value = true;
  if (chatMessages.value.length === 0) {
    analyzeData();
  }
};

// 导出分析
const exportAnalysis = (message) => {
  try {
    // 创建一个Blob对象
    const blob = new Blob([message.content], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    
    // 创建一个下载链接并点击它
    const a = document.createElement('a');
    a.href = url;
    a.download = `${message.analysisType}-${new Date().toLocaleDateString()}.txt`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    
    ElMessage.success('分析报告导出成功');
  } catch (error) {
    console.error('Export failed:', error);
    ElMessage.error('导出失败，请重试');
  }
};

// 分享分析
const shareAnalysis = (message) => {
  ElMessageBox.prompt('请输入接收者邮箱', '分享分析报告', {
    confirmButtonText: '发送',
    cancelButtonText: '取消',
    inputPattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
    inputErrorMessage: '请输入有效的邮箱地址'
  }).then(({ value }) => {
    ElMessage({
      type: 'success',
      message: `分析报告已发送至 ${value}`
    });
  }).catch(() => {
    // 用户取消操作
  });
};

// 生成图表
const generateChart = (message) => {
  chartDialogVisible.value = true;
  
  nextTick(() => {
    if (previewChart) {
      previewChart.dispose();
    }
    
    previewChart = echarts.init(previewChartRef.value);
    
    // 根据分析类型选择不同的图表
    if (message.analysisType === '基础分析') {
      generateBasicAnalysisChart();
    } else if (message.analysisType === '同比分析') {
      generateYoYChart();
    } else if (message.analysisType === '环比分析') {
      generateMoMChart();
    }
  });
};

// 生成基础分析图表
const generateBasicAnalysisChart = () => {
  const option = {
    title: {
      text: '核心指标概览',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['当前值', '环比增长(%)'],
      bottom: '0%'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '15%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: ['用户总数', '订单总数', '商家总数', '景点总数']
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '数量',
        min: 0,
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: '增长率(%)',
        axisLabel: {
          formatter: '{value}%'
        }
      }
    ],
    series: [
      {
        name: '当前值',
        type: 'bar',
        data: [
          metrics.totalUsers,
          metrics.totalOrders,
          metrics.totalMerchants,
          metrics.totalSpots
        ]
      },
      {
        name: '环比增长(%)',
        type: 'line',
        yAxisIndex: 1,
        data: [
          metrics.userGrowth,
          metrics.orderGrowth,
          metrics.merchantGrowth,
          metrics.spotGrowth
        ],
        label: {
          show: true,
          formatter: '{c}%'
        }
      }
    ]
  };
  
  previewChart.setOption(option);
};

// 生成同比图表
const generateYoYChart = () => {
  // 模拟去年数据
  const lastYearData = {
    totalUsers: 38000,
    totalOrders: 10500,
    totalMerchants: 220,
    totalSpots: 145,
  };
  
  const option = {
    title: {
      text: '同比数据对比',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['今年', '去年', '同比增长(%)'],
      bottom: '0%'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '15%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: ['用户总数', '订单总数', '商家总数', '景点总数']
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '数量',
        min: 0,
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: '增长率(%)',
        axisLabel: {
          formatter: '{value}%'
        }
      }
    ],
    series: [
      {
        name: '今年',
        type: 'bar',
        data: [
          metrics.totalUsers,
          metrics.totalOrders,
          metrics.totalMerchants,
          metrics.totalSpots
        ]
      },
      {
        name: '去年',
        type: 'bar',
        data: [
          lastYearData.totalUsers,
          lastYearData.totalOrders,
          lastYearData.totalMerchants,
          lastYearData.totalSpots
        ]
      },
      {
        name: '同比增长(%)',
        type: 'line',
        yAxisIndex: 1,
        data: [
          ((metrics.totalUsers - lastYearData.totalUsers) / lastYearData.totalUsers * 100).toFixed(1),
          ((metrics.totalOrders - lastYearData.totalOrders) / lastYearData.totalOrders * 100).toFixed(1),
          ((metrics.totalMerchants - lastYearData.totalMerchants) / lastYearData.totalMerchants * 100).toFixed(1),
          ((metrics.totalSpots - lastYearData.totalSpots) / lastYearData.totalSpots * 100).toFixed(1)
        ],
        label: {
          show: true,
          formatter: '{c}%'
        }
      }
    ]
  };
  
  previewChart.setOption(option);
};

// 生成环比图表
const generateMoMChart = () => {
  // 模拟上月数据
  const lastMonthData = {
    totalUsers: 44000,
    totalOrders: 12000,
    totalMerchants: 255,
    totalSpots: 152,
  };
  
  const option = {
    title: {
      text: '环比数据对比',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['本月', '上月', '环比增长(%)'],
      bottom: '0%'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '15%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: ['用户总数', '订单总数', '商家总数', '景点总数']
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '数量',
        min: 0,
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: '增长率(%)',
        axisLabel: {
          formatter: '{value}%'
        }
      }
    ],
    series: [
      {
        name: '本月',
        type: 'bar',
        data: [
          metrics.totalUsers,
          metrics.totalOrders,
          metrics.totalMerchants,
          metrics.totalSpots
        ]
      },
      {
        name: '上月',
        type: 'bar',
        data: [
          lastMonthData.totalUsers,
          lastMonthData.totalOrders,
          lastMonthData.totalMerchants,
          lastMonthData.totalSpots
        ]
      },
      {
        name: '环比增长(%)',
        type: 'line',
        yAxisIndex: 1,
        data: [
          ((metrics.totalUsers - lastMonthData.totalUsers) / lastMonthData.totalUsers * 100).toFixed(1),
          ((metrics.totalOrders - lastMonthData.totalOrders) / lastMonthData.totalOrders * 100).toFixed(1),
          ((metrics.totalMerchants - lastMonthData.totalMerchants) / lastMonthData.totalMerchants * 100).toFixed(1),
          ((metrics.totalSpots - lastMonthData.totalSpots) / lastMonthData.totalSpots * 100).toFixed(1)
        ],
        label: {
          show: true,
          formatter: '{c}%'
        }
      }
    ]
  };
  
  previewChart.setOption(option);
};

// 监听窗口大小变化，调整图表
window.addEventListener('resize', () => {
  if (previewChart) {
    previewChart.resize();
  }
});

// 基础分析
const analyzeData = async () => {
  isAnalyzing.value = true;
  const analysis = [];

  try {
    // 分析用户数据
    const userGrowthRate = ((metrics.userGrowth || 0) / 100).toFixed(2);
    analysis.push(`用户增长分析：
- 当前用户总数：${metrics.totalUsers}
- 环比增长率：${userGrowthRate > 0 ? "+" : ""}${(userGrowthRate * 100).toFixed(1)}%
- ${userGrowthRate > 0.1 ? "增长强劲" : userGrowthRate > 0 ? "稳定增长" : "需要关注增长问题"}`);

    // 分析订单数据
    const orderGrowthRate = ((metrics.orderGrowth || 0) / 100).toFixed(2);
    analysis.push(`订单情况分析：
- 订单总量：${metrics.totalOrders}
- 环比变化：${orderGrowthRate > 0 ? "+" : ""}${(orderGrowthRate * 100).toFixed(1)}%
- ${orderGrowthRate > 0.1 ? "订单量显著提升" : orderGrowthRate > 0 ? "订单量平稳" : "订单量下降，建议关注"}`);

    // 分析商家数据
    const merchantGrowthRate = ((metrics.merchantGrowth || 0) / 100).toFixed(2);
    analysis.push(`商家发展分析：
- 商家总数：${metrics.totalMerchants}
- 环比变化：${merchantGrowthRate > 0 ? "+" : ""}${(merchantGrowthRate * 100).toFixed(1)}%
- ${merchantGrowthRate > 0.05 ? "商家数量稳步增长" : merchantGrowthRate > 0 ? "商家增长缓慢" : "商家数量下降，需要关注"}`);

    // 分析景点数据
    const spotGrowthRate = ((metrics.spotGrowth || 0) / 100).toFixed(2);
    analysis.push(`景点运营分析：
- 景点总数：${metrics.totalSpots}
- 环比变化：${spotGrowthRate > 0 ? "+" : ""}${(spotGrowthRate * 100).toFixed(1)}%
- ${spotGrowthRate > 0 ? "景点数量增长" : "景点数量下降，建议评估原因"}`);

    // 综合建议
    const suggestions = [];
    if (userGrowthRate < 0.05) suggestions.push("建议加强用户获取和留存策略");
    if (orderGrowthRate < 0.05)
      suggestions.push("可以考虑推出促销活动刺激订单量");
    if (merchantGrowthRate < 0.02)
      suggestions.push("需要优化商家引入和服务政策");
    if (spotGrowthRate < 0) suggestions.push("建议评估景点质量和用户反馈");

    if (suggestions.length > 0) {
      analysis.push("\n运营建议：\n" + suggestions.join("\n"));
    }

    // 更新消息，添加到历史记录
    chatMessages.value.unshift({
      type: "assistant",
      analysisType: "基础分析",
      content: analysis.join("\n\n"),
      time: new Date().toLocaleTimeString(),
    });

    // 滚动到顶部
    await nextTick();
    if (chatContainer.value) {
      chatContainer.value.scrollTop = 0;
    }

    ElMessage.success("数据分析完成");
  } catch (error) {
    console.error("Analysis failed:", error);
    ElMessage.error("数据分析失败，请重试");
  } finally {
    isAnalyzing.value = false;
  }
};

// 同比分析
const analyzeYearOverYear = async () => {
  isAnalyzingYoY.value = true;
  try {
    const analysis = [];

    // 模拟同比数据（实际项目中需要从后端获取）
    const lastYearData = {
      totalUsers: 38000,
      totalOrders: 10500,
      totalMerchants: 220,
      totalSpots: 145,
    };

    // 计算同比增长率
    const userYoYGrowth = (
      ((metrics.totalUsers - lastYearData.totalUsers) /
        lastYearData.totalUsers) *
      100
    ).toFixed(1);
    const orderYoYGrowth = (
      ((metrics.totalOrders - lastYearData.totalOrders) /
        lastYearData.totalOrders) *
      100
    ).toFixed(1);
    const merchantYoYGrowth = (
      ((metrics.totalMerchants - lastYearData.totalMerchants) /
        lastYearData.totalMerchants) *
      100
    ).toFixed(1);
    const spotYoYGrowth = (
      ((metrics.totalSpots - lastYearData.totalSpots) /
        lastYearData.totalSpots) *
      100
    ).toFixed(1);

    analysis.push(`同比分析报告：

用户同比分析：
- 当前用户数：${metrics.totalUsers}
- 去年同期：${lastYearData.totalUsers}
- 同比增长：${userYoYGrowth}%
- ${userYoYGrowth > 15 ? "用户增长显著" : userYoYGrowth > 0 ? "用户稳定增长" : "用户增长承压"}

订单同比分析：
- 当前订单数：${metrics.totalOrders}
- 去年同期：${lastYearData.totalOrders}
- 同比增长：${orderYoYGrowth}%
- ${orderYoYGrowth > 15 ? "订单增长强劲" : orderYoYGrowth > 0 ? "订单平稳增长" : "订单量需关注"}

商家同比分析：
- 当前商家数：${metrics.totalMerchants}
- 去年同期：${lastYearData.totalMerchants}
- 同比增长：${merchantYoYGrowth}%
- ${merchantYoYGrowth > 10 ? "商家拓展显著" : merchantYoYGrowth > 0 ? "商家稳定增长" : "商家发展承压"}

景点同比分析：
- 当前景点数：${metrics.totalSpots}
- 去年同期：${lastYearData.totalSpots}
- 同比增长：${spotYoYGrowth}%
- ${spotYoYGrowth > 5 ? "景点拓展良好" : spotYoYGrowth > 0 ? "景点稳定增长" : "景点发展需优化"}

年度发展建议：
${userYoYGrowth < 10 ? "- 建议加大用户获取力度\n" : ""}${orderYoYGrowth < 10 ? "- 可考虑优化订单转化率\n" : ""}${merchantYoYGrowth < 5 ? "- 需加强商家引入和支持\n" : ""}${spotYoYGrowth < 5 ? "- 建议完善景点质量评估" : ""}`);

    // 添加到历史记录
    chatMessages.value.unshift({
      type: "assistant",
      analysisType: "同比分析",
      content: analysis.join("\n"),
      time: new Date().toLocaleTimeString(),
    });

    ElMessage.success("同比分析完成");
  } catch (error) {
    console.error("YoY analysis failed:", error);
    ElMessage.error("同比分析失败，请重试");
  } finally {
    isAnalyzingYoY.value = false;
  }
};

// 环比分析
const analyzeMonthOverMonth = async () => {
  isAnalyzingMoM.value = true;
  try {
    const analysis = [];

    // 模拟上月数据（实际项目中需要从后端获取）
    const lastMonthData = {
      totalUsers: 44000,
      totalOrders: 12000,
      totalMerchants: 255,
      totalSpots: 152,
    };

    // 计算环比增长率
    const userMoMGrowth = (
      ((metrics.totalUsers - lastMonthData.totalUsers) /
        lastMonthData.totalUsers) *
      100
    ).toFixed(1);
    const orderMoMGrowth = (
      ((metrics.totalOrders - lastMonthData.totalOrders) /
        lastMonthData.totalOrders) *
      100
    ).toFixed(1);
    const merchantMoMGrowth = (
      ((metrics.totalMerchants - lastMonthData.totalMerchants) /
        lastMonthData.totalMerchants) *
      100
    ).toFixed(1);
    const spotMoMGrowth = (
      ((metrics.totalSpots - lastMonthData.totalSpots) /
        lastMonthData.totalSpots) *
      100
    ).toFixed(1);

    analysis.push(`环比分析报告：

用户环比分析：
- 当前用户数：${metrics.totalUsers}
- 上月数据：${lastMonthData.totalUsers}
- 环比增长：${userMoMGrowth}%
- ${userMoMGrowth > 5 ? "用户增长迅速" : userMoMGrowth > 0 ? "用户稳定增长" : "用户增长放缓"}

订单环比分析：
- 当前订单数：${metrics.totalOrders}
- 上月数据：${lastMonthData.totalOrders}
- 环比增长：${orderMoMGrowth}%
- ${orderMoMGrowth > 5 ? "订单增长显著" : orderMoMGrowth > 0 ? "订单平稳增长" : "订单量下降"}

商家环比分析：
- 当前商家数：${metrics.totalMerchants}
- 上月数据：${lastMonthData.totalMerchants}
- 环比增长：${merchantMoMGrowth}%
- ${merchantMoMGrowth > 3 ? "商家增长良好" : merchantMoMGrowth > 0 ? "商家稳定增长" : "商家数量下降"}

景点环比分析：
- 当前景点数：${metrics.totalSpots}
- 上月数据：${lastMonthData.totalSpots}
- 环比增长：${spotMoMGrowth}%
- ${spotMoMGrowth > 2 ? "景点发展良好" : spotMoMGrowth > 0 ? "景点稳定增长" : "景点数量减少"}

月度优化建议：
${userMoMGrowth < 3 ? "- 建议优化用户留存策略\n" : ""}${orderMoMGrowth < 3 ? "- 可考虑短期促销活动\n" : ""}${merchantMoMGrowth < 2 ? "- 需要提升商家服务体验\n" : ""}${spotMoMGrowth < 1 ? "- 建议评估景点运营状况" : ""}`);

    // 添加到历史记录
    chatMessages.value.unshift({
      type: "assistant",
      analysisType: "环比分析",
      content: analysis.join("\n"),
      time: new Date().toLocaleTimeString(),
    });

    ElMessage.success("环比分析完成");
  } catch (error) {
    console.error("MoM analysis failed:", error);
    ElMessage.error("环比分析失败，请重试");
  } finally {
    isAnalyzingMoM.value = false;
  }
};
</script>

<style lang="scss" scoped>
.operation-statistics {
  padding: 20px;
}

.main-content {
  width: 100%;
}

.dialog-header {
  padding-bottom: 16px;
  margin-bottom: 16px;
  border-bottom: 1px solid var(--el-border-color-light);
  display: flex;
  flex-direction: column;
  gap: 12px;

  .header-title {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 16px;
    font-weight: bold;
    color: var(--el-text-color-primary);
  }

  .header-actions {
    display: flex;
    justify-content: center;
    gap: 8px;
  }
}

.chat-container {
  max-height: 400px;
  overflow-y: auto;
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin: 0 -20px;
  padding: 0 20px;
}

.message {
  max-width: 100%;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 12px;
  background-color: var(--el-fill-color-light);
  border: 1px solid var(--el-border-color-lighter);

  .message-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;

    .message-type {
      font-weight: bold;
      color: var(--el-color-primary);
    }

    .message-time {
      font-size: 12px;
      color: var(--el-text-color-secondary);
    }
  }

  .message-content {
    white-space: pre-wrap;
    word-break: break-word;
    color: var(--el-text-color-primary);
    font-size: 14px;
    line-height: 1.6;
  }
}

.input-container {
  display: none;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.core-metrics {
  margin-bottom: 20px;
}

:deep(.el-card) {
  transition: all 0.3s ease;
  border: none;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }

  .el-card__header {
    border-bottom: 1px solid var(--el-border-color-light);
    padding: 15px 20px;
  }
}

.metric-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .el-tag {
    padding: 4px 8px;
    border-radius: 4px;
  }
}

.metric-value {
  font-size: 28px;
  font-weight: bold;
  margin: 15px 0;
  color: var(--el-text-color-primary);
  transition: color 0.3s ease;
}

.metric-compare {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  display: flex;
  align-items: center;
  gap: 4px;
}

.up {
  color: var(--el-color-success);
  display: flex;
  align-items: center;
  gap: 4px;

  &::after {
    content: "↑";
    font-size: 12px;
  }
}

.down {
  color: var(--el-color-danger);
  display: flex;
  align-items: center;
  gap: 4px;

  &::after {
    content: "↓";
    font-size: 12px;
  }
}

.charts-container {
  margin: 20px 0;
}

.chart-wrapper {
  background: var(--el-bg-color);
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 var(--el-box-shadow-light);
  margin-bottom: 20px;
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 4px 16px 0 var(--el-box-shadow);
  }
}

.chart-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 20px;
  color: var(--el-text-color-primary);
}

.chart {
  height: 300px;
  transition: all 0.3s ease;
}

.mt-4 {
  margin-top: 20px;
}

/* 暗黑模式适配 */
html[data-theme="dark"] {
  .operation-statistics {
    background-color: var(--el-bg-color);
  }

  :deep(.el-card) {
    background-color: var(--el-bg-color-overlay);
    border: 1px solid var(--el-border-color-darker);

    &:hover {
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
    }
  }

  .chart-wrapper {
    background-color: var(--el-bg-color-overlay);
    border: 1px solid var(--el-border-color-darker);
  }

  .metric-value {
    color: var(--el-text-color-primary);
  }

  .metric-compare {
    color: var(--el-text-color-secondary);
  }

  .message {
    &.assistant {
      background-color: var(--el-bg-color);
      color: var(--el-text-color-primary);
    }
  }
}

/* AI分析模态框样式 */
:deep(.ai-analysis-dialog) {
  .el-dialog__header {
    padding: 0;
    margin: 0;
  }
  
  .el-dialog__body {
    padding: 0;
  }
  
  .el-dialog__headerbtn {
    z-index: 10;
  }
}

.analysis-dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 20px 15px;
  background: linear-gradient(135deg, var(--el-color-primary-light-7), var(--el-color-primary-light-9));
  border-radius: 8px 8px 0 0;
  
  .header-left {
    display: flex;
    align-items: center;
    gap: 12px;
    
    .ai-avatar {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      background-color: var(--el-color-primary);
      color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      
      .el-icon {
        font-size: 22px;
      }
    }
    
    .header-title {
      display: flex;
      flex-direction: column;
      
      span {
        font-size: 18px;
        font-weight: bold;
        color: var(--el-color-primary-dark-2);
      }
      
      .header-subtitle {
        font-size: 12px;
        color: var(--el-text-color-secondary);
        margin-top: 4px;
      }
    }
  }
  
  .header-actions {
    .el-button {
      padding: 8px 12px;
    }
  }
}

.analysis-dialog-body {
  padding: 20px;
  max-height: 60vh;
  overflow-y: auto;
  
  .analysis-messages {
    display: flex;
    flex-direction: column;
    gap: 16px;
  }
}

.message {
  position: relative;
  padding: 16px 20px;
  border-radius: 8px;
  background-color: var(--el-fill-color-light);
  border-left: 4px solid var(--el-color-primary);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  
  &:hover {
    box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
    transform: translateY(-2px);
  }
  
  &.同比分析 {
    border-left-color: var(--el-color-info);
  }
  
  &.环比分析 {
    border-left-color: var(--el-color-success);
  }
  
  .message-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    
    .message-left {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .message-icon {
        width: 24px;
        height: 24px;
        border-radius: 50%;
        background-color: var(--el-color-primary-light-8);
        color: var(--el-color-primary);
        display: flex;
        align-items: center;
        justify-content: center;
      }
      
      .message-type {
        font-weight: bold;
        color: var(--el-color-primary);
      }
    }
    
    .message-time {
      font-size: 12px;
      color: var(--el-text-color-secondary);
    }
  }
  
  .message-content {
    white-space: pre-wrap;
    word-break: break-word;
    color: var(--el-text-color-primary);
    font-size: 14px;
    line-height: 1.6;
    margin-bottom: 12px;
  }
  
  .message-actions {
    display: flex;
    justify-content: flex-end;
    padding-top: 8px;
    border-top: 1px dashed var(--el-border-color-lighter);
  }
}

.analysis-dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  
  .ai-powered {
    font-size: 12px;
    color: var(--el-text-color-secondary);
    display: flex;
    align-items: center;
    gap: 5px;
    
    &::before {
      content: '';
      display: block;
      width: 8px;
      height: 8px;
      border-radius: 50%;
      background-color: var(--el-color-success);
    }
  }
}

.chart-preview {
  width: 100%;
  height: 400px;
}
</style>
